<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="院（部）" prop="faculty">
            <el-input v-model="formData.faculty" placeholder="请输入院（部）"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="专业" prop="major">
            <el-input v-model="formData.major" placeholder="请输入专业"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="组别" prop="groupType">
            <el-input v-model="formData.groupType" placeholder="请输入组别"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="年级及班级" prop="className">
            <el-input v-model="formData.className" placeholder="请输入年级及班级"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名" prop="stuName">
            <el-input v-model="formData.stuName" placeholder="请输入姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学号" prop="stuNo">
            <el-input v-model="formData.stuNo" placeholder="请输入学号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="指导教师" prop="tutor">
            <el-input v-model="formData.tutor" placeholder="请输入指导教师名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="项目类别" prop="projectType">
            <el-input v-model="formData.projectType" placeholder="请输入项目类别"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实验时间" prop="trainingTime">
            <el-date-picker
              v-model="formData.trainingTime"
              type="datetime"
              placeholder="请选择时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              style="width: 100% !important;"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验地点" prop="trainingWhere">
            <el-input v-model="formData.trainingWhere" placeholder="请输入实验地点"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="实验项目" prop="proId">
            <el-select
              v-model="formData.proId"
              placeholder="请选择"
              ref="select"
              popper-class="select-popper"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="目的及要求" prop="expPurpose">
            <el-input v-model="formData.expPurpose" type="textarea" rows="4"
                      placeholder="请输入目的及要求"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="内容" prop="expContent">
            <el-input v-model="formData.expContent" type="textarea" rows="4"
                      placeholder="请输入实验内容"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="步骤" prop="trainingStep">
            <el-input v-model="formData.trainingStep" type="textarea" rows="4"
                      placeholder="请编写实验步骤"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="实验结论及总结" prop="conclusion">
            <el-input v-model="formData.conclusion" type="textarea" rows="4"
                      placeholder="请输入实验结论及总结"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {CommonStatusEnum} from '@/utils/constants'
import * as RoleApi from '@/api/system/role'
import * as ReportApi from '@/api/laboratory/report'
import {addReport, getReport, studentAddReport,getCurrentInfo} from "@/api/laboratory/report";
import {any, number} from "vue-types";
import * as ProjectApi from "@/api/laboratory/project";

defineOptions({name: 'SystemRoleForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const projectList = ref([])
const projectTotal = ref(0)
const projectQuery = reactive({
  pageNo: 1,
  pageSize: 10
})
let dropdownWrap = null;
let userId = JSON.parse(JSON.parse(localStorage.getItem("user")).v).user.id
let queryType = JSON.parse(JSON.parse(localStorage.getItem("user")).v).roles[0]
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  proId: "",
  stuId:userId,
  expContent: "",
  score: "",
  conclusion: "",
  teaSum: "",
  tutor: "",
  name: "",
  expPurpose: "",
  expRequest: "",
  stuName: "",
  className: "",
  major: "",
  faculty: "",
  stuNo: "",
  groupType: "",
  projectType: "",
  trainingTime: "",
  trainingWhere: "",
  trainingStep: "",
  isFilled: undefined,
})
const formRules: any = reactive({ //表单校验
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  console.log(JSON.parse(JSON.parse(localStorage.getItem("user")).v))
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ReportApi.getReport(id)
      formData.value = data.result
    } finally {
      formLoading.value = false
    }
  }
}

const getProjectList = async () => {
  try {
    const data = await ProjectApi.getProjectPage(projectQuery)
    projectList.value = data.result
    projectTotal.value = data.total
  } finally {
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    proId: "",
    stuId:userId,
    expContent: "",
    score: "",
    conclusion: "",
    teaSum: "",
    tutor: "",
    name: "",
    expPurpose: "",
    expRequest: "",
    stuName: "",
    className: "",
    major: "",
    faculty: "",
    stuNo: "",
    groupType: "",
    projectType: "",
    trainingTime: "",
    trainingWhere: "",
    trainingStep: "",
    isFilled: undefined,
  }
  formRef.value?.resetFields()

}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RoleApi.RoleVO
    if (formType.value === 'create') {
      await ReportApi.studentAddReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await ReportApi.studentUpdateReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}


const handleScroll = () => {
    if (dropdownWrap) {
      const {scrollTop, scrollHeight, clientHeight} = dropdownWrap;
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log('到达底部');
        // 滚动条到达底部的处理逻辑，例如加载更多数据
        projectQuery.pageSize += 10
        getProjectList()
      }
    }
  }
;
const updateDropdownWrap = () => {
  dropdownWrap = document.querySelector('.select-popper .el-select-dropdown__wrap');
  if (dropdownWrap) {
    dropdownWrap.addEventListener('scroll', handleScroll);
  }
};


onMounted(() => {
  getProjectList()
  nextTick(() => {
    updateDropdownWrap();
  });
})

onBeforeUnmount(() => {
  if (dropdownWrap) {
    dropdownWrap.removeEventListener('scroll', handleScroll);
  }
});


</script>
